﻿#region Header

/*
Remote views based on linq
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System.Reflection;
using Sebarf.Services.Interfaces;
using Sebastof.Services.Interfaces;

#endregion

namespace Sebastof.Services.Impl {
	/// <summary>
	/// Default implementation for the IChangeApplierService.
	/// </summary>
	public class ChangeApplierService : Service, IChangeApplierService {
		private static BindingFlags TraceFields = BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.Public |
												  BindingFlags.NonPublic;

		#region IChangeApplierService Members

		/// <summary>
		/// Sets a field of an object to a new value.
		/// If the object is an implementation ApplicationObject we set the value directly, else we use
		/// reflection to set the new value.
		/// </summary>
		/// <param name="objectToChange"></param>
		/// <param name="nameOfFieldToChange"></param>
		/// <param name="newValueOfField"></param>
		public void SetValue(object objectToChange, string nameOfFieldToChange, object newValueOfField) {
			//first, try for application object
			var interlinqobj = objectToChange as ISebastofApplicationObject;
			if (interlinqobj != null) {
				interlinqobj.SetValue(nameOfFieldToChange, newValueOfField);
			}
			else {
				//get field of object
				FieldInfo field = objectToChange.GetType().GetField(nameOfFieldToChange, TraceFields);
				if (field != null) {
					field.SetValue(objectToChange, newValueOfField);
				}
				else {
					//if it was not a field, it has to be a property, else we crash ;)
					PropertyInfo prop = objectToChange.GetType().GetProperty(nameOfFieldToChange, TraceFields);
					prop.SetValue(objectToChange, newValueOfField, null);
				}
			}
		}

		#endregion
	}
}